import time, re
import pandas as pd
import sys

sys.path.append('../')
import pre_api_xr
import json


def Add_pro(api_):
    intro_before = '<p><strong>产品说明书</strong></p><table bgcolor="#CCC" border="0" cellpadding="2" cellspacing="1" width="100%"><tbody><tr class="firstRow"><td bgcolor="#EFEFEF" nowrap="nowrap" width="56" height="40" align="center">nnnnme</td><td bgcolor="#FFFFFF" nowrap="nowrap" width="405" height="40" style="text-indent:8px;"><a href="pdfurl" target="_blank" style="text-decoration: underline;">nnnnme</a></td></tr></tbody></table>'
    intro_add = ''
    t = time.strftime("%Y-%m-%d%H%M%S", time.localtime(int(time.time())))
    with open('../get_json/Product.json', encoding='utf-8') as data_json:
        con_dict = json.load(data_json)
    df = pd.read_csv('../../spider/final_csv/biosharp_list1.csv')
    df = df.iloc[0,5]
    # df = df[~(df['cart'] == '商品已停售')]
    # df['mktprice'] =df['price']
    df.rename(columns={'price': 'price_sold', 'unit': 'spec'}, inplace=True)
    # df = df.iloc[30782,]
    for i in range(len(df)):
        # time.sleep(0.5)
        content = con_dict.copy()
        df_con = df.iloc[i,].to_dict()
        # img_brand = df_con['imgs']
        img_list = df_con['album']
        if isinstance(df_con['productmanual'], float):
            df_con['productmanual'] = ' '
        intro_before_add = intro_before.replace('nnnnme', df_con['name'], 2).replace('pdfurl','https://www.beyotime.com' + df_con['productmanual'])
        # while len(img_list) < 4:
        #     img_list.append(img_brand)
        # while len(img_list) < 5:
        #     img_list.append('https://images.rjmart.cn/image/5b7e3821/06556c43-e64a-4b4c-ab26-b379e844f241.png')
        if df_con['price_sold'] >= df_con['mktprice']:
            df_con['mktprice'] = df_con['mktprice'] + 2 * (df_con['price_sold'] - df_con['mktprice'])
        content.update(
            {'productNum': df_con['bn'].replace(' ', ''), 'price': df_con['price_sold'],
             'directoryPrice': df_con['mktprice'],
             'name': df_con['name'], 'specification': df_con['spec'],
             'status': 3,
###############
             'categoryId': df_con['rjmart_id'],
             'brandId': 65, 'sku': 2000, "deliveryTime": 1,
             'unit': '件', 'desc': intro_before_add + '<p><br/></p>' + df_con['intro'] + intro_add, 'photos': img_list,
        #########     'carryFeeTemplateId': 2854
             })
        content = json.dumps(content)
        # print(content)
        # rj_api = pre_api_xr.pre_api_get()
        response = api_.saveOrUpdateProduct(content)
        result = response.content.decode('utf-8')
        # print(response)
        print(result)
        with open(f'../get_json/AddProduct{t}.txt', 'a', encoding='utf-8') as f:
            f.write(df_con['code'] + '\t')
            f.write(result)
            # f.write(response)
            f.write('\n')


if __name__ == '__main__':
    # rj_api = pre_api_xr.pre_api_get()
    # Add_pro(rj_api)

    df = pd.read_csv('../../spider/final_csv/biosharp_list.csv',usecols=['name','cat_name'])
    df.drop_duplicates(subset=['cat_name'], keep='first', inplace=True)
    print(df)
    df.to_excel('../../final_up/biosharp_cate.xlsx')



    # Update_pro()
    # df = pd.read_csv('../../final_up/beyotime_detail0605.csv')
    # print(df)
    # df_add = pd.read_excel('../../final_up/beyotime_cate.xlsx',usecols=['cate','rjmart_id'])
    # df = df.merge(df_add, how='inner', on='cate')
    # print(df.iloc[5, ])
    # df.to_csv('../../final_up/beyotime_rj0605.csv', encoding='utf-8', index=False)
    # df = df.loc[df.code.str.contains('ST828-100ml')]
    # df.dropna(axis=0, inplace=True)
    # df.drop_duplicates(subset=['cart'], keep='first', inplace=True)
    # print(df)
    # df.to_excel('../../final_up/beyotime_cate.xlsx')
